package br.com.megaacerto.controle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import br.com.megaacerto.dto.UsuarioLogadoDTO;

import com.google.gson.Gson;

public class AtualizaSaldoControle extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {	
		
		String usuario = ((UsuarioLogadoDTO) req.getSession().getAttribute("usuario")).getEmail();
		String senha   = ((UsuarioLogadoDTO) req.getSession().getAttribute("usuario")).getSenha();
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://localhost:8080/restservice/usuario/login");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("email", usuario));
		nameValuePairs.add(new BasicNameValuePair("senha", senha));
		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse httpResponse = httpClient.execute(httpPost);
		BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
		String linha = "";
		UsuarioLogadoDTO usuarioLogadoDTO = null;
		Gson gson = new Gson();
		
		while ((linha = rd.readLine()) != null) {
			usuarioLogadoDTO = gson.fromJson(linha, UsuarioLogadoDTO.class);
		}
		
		if(usuarioLogadoDTO != null && (usuarioLogadoDTO.isLogadoAdmin() || usuarioLogadoDTO.isLogadoUser()) ){
			req.getSession().setAttribute("usuario", usuarioLogadoDTO);
		}		
	}
}
